package com.xiaoran.springboot3.RegistBean;

import com.xiaoran.springboot3.servlet.MyFilter;
import com.xiaoran.springboot3.servlet.Myservlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@Slf4j
public class MyRegistConfig {
    @Bean
    public ServletRegistrationBean myservlet(){
        HttpServlet httpServlet=new HttpServlet() {
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                resp.getWriter().write("小冉------6666666");
            }
        };
        return new ServletRegistrationBean(httpServlet,"/my");

    }

    @Bean
    public FilterRegistrationBean myFilter(){
        Filter filter=new Filter() {
            @Override
            public void init(FilterConfig filterConfig) throws ServletException {
                log.error("小冉开始初始化。。。。。。。。。。。。。");
            }

            @Override
            public void destroy() {
                log.error("小冉开始销毁了。。。。。。。。。。。。。");
            }

            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                log.error("小冉开始上班了************************");
                chain.doFilter(request,response);
            }
        };
        /*第一种写法
        ServletRegistrationBean url=new ServletRegistrationBean();
        url.addUrlMappings("/my");
        return new FilterRegistrationBean(filter,url);
        */
        //第二种拦截方法
        return new FilterRegistrationBean(filter,myservlet());
    }


    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean(){

        ServletContextListener servletContextListener=new ServletContextListener() {
            @Override
            public void contextInitialized(ServletContextEvent sce) {
                log.error("项目开始初始化-----------------------");
            }

            @Override
            public void contextDestroyed(ServletContextEvent sce) {
                log.error("项目开始销毁******************************");
            }
        };

        return new ServletListenerRegistrationBean(servletContextListener);
    }
}
